package com.example.shop.service.impl;

import com.example.shop.domain.Address;
import com.example.shop.enums.AddressEnum;
import com.example.shop.repository.AddressRepository;
import com.example.shop.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by cx on 17-12-7.
 */
@Service
public class AddressServiceImpl implements AddressService {


    @Autowired
    private AddressRepository addressRepository;

    @Override
    public void changeStatus(String openid, String addressid) {

        List<Address> addressList = addressRepository.findByOpenid(openid);

        for (Address address : addressList) {
            if (!address.getId().equals(addressid)){
                address.setStatus(AddressEnum.UNDEFUALT.getCode());
            }
            else {
                address.setStatus(AddressEnum.DEFUALT.getCode());
            }
        }
        addressRepository.save(addressList);



    }

    /*增加地址*/
    @Override
    public void addAddress(String openid, Address address) {

        address.setOpenid(openid);
        addressRepository.save(address);
    }

    /*删除地址*/
    @Override
    public void delAddress(String openid, String addressId) {

        Integer rs =addressRepository.findOne(addressId).getStatus();
        if (rs.equals(AddressEnum.DEFUALT)){
            for (Address address: addressRepository.findByOpenid(openid)){
                if (!(address.getId().equals(addressId))){
                    address.setStatus(AddressEnum.DEFUALT.getCode());
                    break;
                }
            }
        }
        addressRepository.delete(addressId);
    }

    @Override
    public Address findOne(String addressid) {
        Address address = addressRepository.findOne(addressid);
        return address;
    }

    @Override
    public void update(String addressid, Address address) {
        String openid = addressRepository.findOne(addressid).getOpenid();
        addressRepository.delete(addressid);
        address.setOpenid(openid);
        addressRepository.save(address);

    }

    @Override
    public List<Address> findByOpenid(String openid) {
        return addressRepository.findByOpenid(openid);
    }


}
